﻿using AutoMapper;
using System;

namespace OkTool.Mapper
{
    public static class AutoMapperUtil
    {
        /// <summary>
        /// 映射
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="obj">源对象</param>
        /// <returns></returns>
        public static T Map<T>(this object obj)
        {
            if (obj == null) throw new Exception("异常");
            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap(obj.GetType(), typeof(T));
            });
            var mapper = config.CreateMapper();
            return mapper.Map<T>(obj);
        }
        /// <summary>
        /// 映射
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj">源对象</param>
        /// <param name="entity">目标对象</param>
        /// <param name="ignoreNull">忽略null</param>
        /// <returns></returns>
        public static T Map<T>(object obj, T entity, bool ignoreNull = true)
        {
            var config = new MapperConfiguration(cfg =>
            {
                if (ignoreNull)
                {
                    CreateMappingsInternal(cfg);
                }
                cfg.CreateMap(obj.GetType(), typeof(T));
            });
            var mapper = config.CreateMapper();
            return mapper.Map(obj, entity);
        }
        private static void CreateMappingsInternal(IMapperConfigurationExpression cfg)
        {
            //没错就是这句话
            cfg.ForAllMaps((a, b) => b.ForAllMembers(opt => opt.Condition((src, dest, sourceMember) => sourceMember != null)));
        }

    }
}